; (function (window, $) {
  util.needMemberLogin()

  $(function () {
    $('img#index-headshow').attr(
      'src',
      localStorage.avatar || '/assets/images/default-avatar.png'
    )
    $('span#index-name').text(localStorage.name)
    $('span#nav-name').text(localStorage.name || localStorage.phone)
    $('span#index-phone').text(localStorage.phone)

    if (window.location.hash === '') {
      loadpage('application')
    } else {
      loadpage(window.location.hash.substring(1))
    }

    $('.menu-f').on('click', function () {
      $(this).toggleClass('close')
    })

    $('a.page').on('click', function () {
      var pagename = $(this).data('name')
      window.history.pushState({}, null, '/my#' + pagename)
      loadpage(pagename)
    })

    $(window).on('popstate', function () {
      // console.log(window.location.hash.substring(1))
      loadpage(window.location.hash.substring(1))
    })

    // logout
    $('#nav_logout').on('click', function () {
      localStorage.clear()
      window.top.location.reload()
    })
  })

  function loadpage(pagename) {
    $.ajax({
      url: '/my/' + pagename + '.html',
      type: 'GET',
      dataType: 'html',
      success: function (data) {
        $('#router-view').html(data)
      }
    })
  }

  // export a function to window
  window.flushInfo = function () {
    util.ajax({
      url: '/user/member',
      type: 'GET',
      success: function (res) {
        // save userinfo into localstorage
        for (var item in res.data) {
          localStorage.setItem(item, res.data[item])
        }

        $('img#index-headshow').attr(
          'src',
          localStorage.avatar || '/assets/images/default-avatar.png'
        )
        $('span#index-name').text(localStorage.name)
        $('span#nav-name').text(localStorage.name || localStorage.phone)
        $('span#index-phone').text(localStorage.phone)
      }
    })
  }
})(window, jQuery)
